#include "ServerSocket.h"

ServerSocket::ServerSocket(const SocketSettings& settings, const QString& name)
: _settings(settings)
, _server(new QTcpServer())
, _socket(0)
{
    _server->listen(QHostAddress(_settings.host), _settings.port);
    _server->setMaxPendingConnections(1);
    connect(_server.get(), SIGNAL(newConnection()), this, SLOT(ClientConnected()));
}

bool ServerSocket::Open()
{
    return IsOpened();
}

bool ServerSocket::IsOpened()
{
    return _socket && _socket->isValid() && (_socket->state() == QAbstractSocket::ConnectedState);
}

void ServerSocket::Reset()
{
    _socket = 0;
}

void ServerSocket::Close()
{
    _socket->disconnectFromHost();
    _server->close();
}

void ServerSocket::ClientConnected()
{
     _socket = _server->nextPendingConnection();

     connect(_socket, SIGNAL(readyRead()), this, SLOT(HasData()));
     connect(_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
     connect(_socket, SIGNAL(disconnected()), _socket, SLOT(deleteLater()));
}

unsigned ServerSocket::DataAvailable()
{
    return _socket->bytesAvailable();
}

QString ServerSocket::LastError()
{
    return QString(_server->errorString());
}

QString ServerSocket::Info()
{
    return QString("Server TCP socket: %2@%1").arg(_settings.host, QString("%1").arg(_settings.port));
}

QByteArray ServerSocket::Receive(unsigned size)
{
    return _socket->read(size);
}

unsigned ServerSocket::Send(const QByteArray& data)
{
    return _socket->write(data);
}